package com.qingding.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.qingding.R;
import com.qingding.activity.AddFriendsActivity;
import com.qingding.activity.ChatActivity;
import com.qingding.activity.LoginActivity;
import com.qingding.activity.SettingActivity;
import com.qingding.adapter.FriendAdapter;
import com.qingding.model.Friend;
import com.qingding.utils.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WoDeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
//看了半天终于知道这个Fragment到底是干什么的了，原来是我的那个界面
public class WoDeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ImageView login_register;
    private TextView login_user;
    private ImageButton setting;
    private ImageButton addfriend;
    private FriendAdapter friendAdapter;
    private RecyclerView recyclerView;
    private String friendName;
    private int photoId;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    //private GridLayoutManager layoutManager;
    private LinearLayoutManager linearLayoutManager;
    private AVUser avUser = AVUser.getCurrentUser();
    private List<Friend> friends;
    private int rightPhotoId ;

    private OnFragmentInteractionListener mListener;

    public WoDeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WoDeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WoDeFragment newInstance(String param1, String param2) {
        WoDeFragment fragment = new WoDeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_wo_de, container, false);

        //登录图标
        login_register = (ImageView) view.findViewById(R.id.login_register);
        login_register.setScaleType(ImageView.ScaleType.CENTER_CROP);
        login_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),LoginActivity.class);
                startActivity(intent);
            }
        });
        //登录网名
        login_user = (TextView) view.findViewById(R.id.login_user);

        //获取到当前登录的用户，并改变用户头像及网名
        if (avUser != null){
            rightPhotoId = avUser.getInt("PhotoId");
            login_register.setImageResource(rightPhotoId);
            login_user.setText(avUser.getUsername());


            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_friends);
            linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,true);
            //initFriends();
            recyclerView.setLayoutManager(linearLayoutManager);

            AVQuery<AVUser> followerQuery = null;
            try {
                followerQuery = avUser.followerQuery(AVUser.class);
            } catch (AVException e) {
                Toast.makeText(getActivity(),"错误",Toast.LENGTH_SHORT).show();
            }
            // AVQuery<AVUser> followerQuery = AVUser.followerQuery(userA.getObjectId(),AVUser.class); 也可以使用这个静态方法来获取非登录用户的好友关系
            followerQuery.findInBackground(new FindCallback<AVUser>() {
                @Override
                public void done(List<AVUser> avObjects, AVException avException) {
                    //Log.d("1515", "1515我在这2");
                    friends = new ArrayList<Friend>();
                    for (AVUser avUser : avObjects){
                        final String friendId = avUser.getObjectId();
                        AVQuery<AVObject> avQuery = new AVQuery<>("_User");
                        avQuery.getInBackground(friendId, new GetCallback<AVObject>() {
                            @Override
                            public void done(AVObject avObject, AVException e) {
                                friendName = avObject.getString("username");
                                photoId = avObject.getInt("PhotoId");
                                String objectId = avObject.getObjectId();
                                Friend friend = new Friend(photoId,friendName, objectId);
                                Log.d("1515", "1515"+friend.getUsername()+" "+friend.getImageId()+" "+friend.getObjectId());
                                friends.add(friend);
                                //Log.d("1515", "1515"+friends.size());
                            }
                        });
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    friendAdapter = new FriendAdapter(friends);
                    friendAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent = new Intent(getContext(),ChatActivity.class);
                            intent.putExtra("leftPhotoId",friends.get(position).getImageId());
                            intent.putExtra("rightPhotoId",rightPhotoId);
                            intent.putExtra("userName",friends.get(position).getUsername());
                            intent.putExtra("objectId",friends.get(position).getObjectId());
                            startActivity(intent);
                        }

                    });
                    recyclerView.setAdapter(friendAdapter);
                    //friendAdapter.notifyDataSetChanged();
                }
            });
        }
        //设置图标,为设置图标添加事件监听器，点击后将启动新的活动
        setting = (ImageButton) view.findViewById(R.id.setting);
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),SettingActivity.class);
                startActivity(intent);
            }
        });

        //添加好友功能，点击后将启动另外一个活动
        addfriend = (ImageButton) view.findViewById(R.id.addfriend);
        addfriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(),AddFriendsActivity.class);
                startActivity(intent);
            }
        });

        //RecycleVeiw，从数据库中读取该用户的好友,并且为其添加事件监听器



//        AVFriendshipQuery query = AVUser.friendshipQuery(userId, SubUser.class);
//        query.include("followee");
//        query.include("follower");
//        query.getInBackground(new AVFriendshipCallback() {
//            @Override
//            public void done(AVFriendship friendship, AVException e) {
//                List<SubUser> followers = friendship.getFollowers(); //获取粉丝
//                List<SubUser> followees = friendship.getFollowees(); //获取关注列表
//                AVUser user = friendship.getUser(); //获取用户对象本身
//            }
//        });




        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    //该方法初始化List
//    private void initFriends(){
//        for (int i=0; i<friends.length; i++){
//            friendList.add(friends[i]);
//        }
//    }

}
